<?php
use \PFT\Db;

if (!isset($_SESSION['account'])) {
	exit(json_encode(array('status' => 0, 'info' => '请先登陆')));
}

include('/var/www/html/new/d/common/func.inc.php');
include('/var/www/html/new/d/module/common/Db.class.php');
$db_conf = include('/var/www/html/new/d/module/common/db.conf.php');
Db::Conf($db_conf['remote_1']);
Db::connect();

$params = array(
	'account' => $_SESSION['account'],
	'title' => isset($_POST['title']) ? safetxt($_POST['title']) : '',
	'show_type' => isset($_POST['types']) ? safetxt($_POST['types']) : '',
	'themes' => isset($_POST['themes']) ? safetxt($_POST['themes']) : '',
	'update_time' => time()
);

//匹配图片内容
$params['img_urls'] = safetxt(json_encode(getAllimg($_POST['imgs'])));

$exists = Db::fetch(
	"select id from pft_b2c_store_config where account=:account limit 1",
	array(':account' => $_SESSION['account'])
);
if ($exists) {
	$res = Db::update($params, 'pft_b2c_store_config', $exists['id']);
} else {
	$res = Db::insert($params, 'pft_b2c_store_config');
}

if ($res) {
	exit(json_encode(array('status' => 1, 'info' => '配置成功')));
} else {
	exit(json_encode(array('status' => 1, 'info' => '配置失败')));
}

/**
 * 匹配图片元素
 * @param  string $data 富文本内容
 * @return [type]       [description]
 */
function getAllimg($data) {
    $img = '';
    preg_match_all(
    	'/([^>].{1,3}<img.*?src=[\'"](.*?)[\'"])|(<a.+?href=(.*?)".*?>(.*?)<\/a>)/is',
    	 $data, 
    	 $match
    );
    return processImgUrl($match[0]);
}

/**
 * 从图片中匹配地址
 * @param  string $data img html
 * @return [type]       [description]
 */
function processImgUrl($data) {
    $res = array();
    foreach ($data as $key => $subject) {
        preg_match_all('/(href|src)="(.*?)"/is', $subject, $match);
        $url = $match[2][0];
        if (count($match[2]) == 2) {
            $res[$key]['url'] = $url;
            $res[$key]['img'] = $match[2][1];
        } else {
            $res[$key]['img'] = $url;
        }

    }
    return $res;
}